from ctypes.wintypes import WORD
from math import inf, ldexp
from operator import index
import time
from turtle import width
from urllib.parse import urljoin

import requests
from lxml import etree
import re
import json
import base64

# 导入Excel工具库
import xlwt

# uname = input("请输入用户名或手机号：")
# password = input("请输入密码：").encode()


class chaoxing():
    def __init__(self, uname='13538321696', password='Zhupeng19') -> None:
    # def __init__(self, uname='19521880344', password='4309031a') -> None:
        # 登录态
        self.requests = requests.session()
        # 课程-班级列表
        self.courseId_jclassIds = {}
        self.stuList = {}
        self.uid = 108432164
        self.uname = uname
        self.password = base64.b64encode(password.encode())
        self.headers = {
            'Host': 'mooc1.chaoxing.com',
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36 Edg/96.0.1054.29',
            'Referer': 'http://fycourse.fanya.chaoxing.com/'
        }

    def login(self):
        data = {
            "fid": "-1",
            "uname": self.uname,
            "password": self.password,
            "refer": "http%3A%2F%2Fi.chaoxing.com",
            "t": "true",
            "forbidotherlogin": "0",
        }
        url = "http://passport2.chaoxing.com/fanyalogin"
        headers = {
            "Referer":
            "http://i.chaoxing.com",
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
        }
        response = self.requests.post(url=url, data=data, headers=headers)
        if json.loads(response.text)["status"]:
            print("登录成功....")
            uid = self.requests.get('http://i.chaoxing.com/').text
            self.uid = re.findall(r".*if\('(\d+)' != ''\){", uid)[0]
            print('self.uid:', self.uid)
            sectionId_url = 'http://fycourse.fanya.chaoxing.com/courselist/mycourse'
            sectionId = etree.HTML(self.requests.get(sectionId_url).text)
            sectionId = sectionId.xpath(
                '//*[@id="selectdd"]/ul/li[1]/@sectionid')[0]
            # print(type(sectionId),sectionId)
            courselist_url = 'http://fycourse.fanya.chaoxing.com/courselist/coursedata?sectionId=' + sectionId
            courselist = etree.HTML(self.requests.get(courselist_url).text)
            courselist = courselist.xpath("/html/body/li/@cid")
            print(courselist)
            for moocId in courselist:
                # 更新Cookie
                url = 'http://fycourse.fanya.chaoxing.com/courselist/opencourse?courseId=%s' % moocId
                self.requests.get(url, headers=headers)
                # 提取班级信息
                url = 'https://mooc1.chaoxing.com/teachingClassManage/teachingClassList?courseId=%s' % moocId
                classId = self.requests.get(url, headers=headers)
                classId = etree.HTML(classId.text)
                classIds = classId.xpath(
                    '//*[@id="classDiv"]/ul[1]/div[2]/li/@clazzid')
                className = classId.xpath(
                    '//*[@id="classDiv"]/ul[1]/div[2]/li/a/@title')
                # 保存 课程：班级
                self.courseId_jclassIds[moocId] = dict(zip(
                    classIds, className))
            print(self.courseId_jclassIds)

            # 保存学生名单
            wb = xlwt.Workbook()
            for x in self.courseId_jclassIds.items():
                ws = wb.add_sheet(x[0])
                row = 0
                self.stuList[x[0]] = []
                for y in x[1].items():
                    for pageNum in [1, 2]:
                        url = "https://mooc1.chaoxing.com/teachingClassManage/teachingClassList?classId=%s&require=&courseId=%s&teachingClassId=&show=&pageNum=%s&classGroupName=&ut=t&cpi=%s&schoolid=-1&schoolName=&orderType=updown" % (
                            y[0], x[0], pageNum, self.get_info(x[0])['cpi'])
                        print(url)
                        stuList = self.requests.get(url=url,
                                                    headers=self.headers)
                        stuList = etree.HTML(stuList.text)
                        stuList = stuList.xpath('//*[@id="allstu"]/tr')
                        for td in stuList:
                            tr = []
                            col = 0
                            for y in td.xpath('td/text()')[3:8]:
                                ws.write(row, col, y.strip())
                                col = col + 1
                                tr.append(y.strip())
                            row = row + 1
                            self.stuList[x[0]].append(tr)
            wb.save('学生名单.xls')
        else:
            print(json.loads(response.text)["msg2"])
            return

    def sign_in(self, excelName='签到'):
        '''签到'''
        # 初始化表格对象
        wb = xlwt.Workbook()
        for courseId in self.courseId_jclassIds.items():  # 多班级循环
            # 创建一个工作表，并命名courseId
            ws = wb.add_sheet(courseId[0])
            row = 0
            for jclassId in courseId[1].items():
                class_list = []
                for page in "123":  # 各班级 签到数据 翻页
                    url = (
                        "http://mobilelearn.chaoxing.com/signStatistics?fid=420&courseId=%s&jclassId=%s&uid=%s&activeType=2&page=%s"
                        % (courseId[0], jclassId[0], self.uid, page))
                    # print('签到班级：',url)

                    html = self.requests.get(url)
                    selector = etree.HTML(html.text)
                    name = selector.xpath(
                        "/html/body/div/div[4]/table/tbody/tr/td[1]/text()")
                    num = selector.xpath(
                        "/html/body/div/div[4]/table/tbody/tr/td[2]/text()")
                    suid = selector.xpath(
                        "/html/body/div/div[4]/table/tbody/tr/td[7]/a/@onclick"
                    )
                    suid = [re.search(r"\d+", str(i)).group() for i in suid]
                    info = [[jclassId[1]] + list(x)
                            for x in zip(name, num, suid)]
                    # print(info)
                    for x in info:
                        url_uid = (
                            "http://mobilelearn.chaoxing.com/signStatistics/signDetail?fid=420&courseId=%s&jclassId=%s&enc=&uid=%s"
                            % (courseId[0], jclassId[0], x[3]))
                        # print('签到页面：',url_uid)
                        u_html = self.requests.get(url_uid)
                        selector_u = etree.HTML(u_html.text)
                        u_list = selector_u.xpath(
                            "/html/body/div/div[2]/div/div/dl/dd/text()")
                        # 数据清洗
                        # print(u_list)
                        u_list = [
                            re.sub("(\r|\n|\t| |\(未参与\）|出勤)", "", i)
                            for i in u_list
                        ]
                        # print(u_list)

                        u_list = [re.sub("事假", "△", i) for i in u_list]
                        u_list = [re.sub("迟到|已过期", "U", i) for i in u_list]
                        u_list = [re.sub("缺勤", "×", i) for i in u_list]
                        u_list = [re.sub("病假", "△", i) for i in u_list]
                        u_list = [re.sub("早退", "*", i) for i in u_list]
                        # print(u_list)
                        # exit()
                        # # begin 合并每2考勤 为 1列
                        # u_list_1 = [
                        #     str(str(u_list[x]) + str(u_list[x + 1]))
                        #     for x in range(0, len(u_list) - 1, 2)
                        # ]
                        # u_list = u_list_1 + [u_list[28]]
                        # # end
                        class_list.append(x + u_list)
                # 遍历数据文件中的所有行
                for dd in class_list:
                    # 初始化列计数器
                    col = 0
                    # 遍历每一行数据的所有列
                    for x in dd:
                        # if col == 1:
                        #     x = int(x)
                        ws.write(row, col, x)
                        # 每添加一列数据，列计数器就+1
                        col = col + 1
                    # 每添加一行数据，行计数器就+1
                    row = row + 1
        # 保存Excel文件，并命名为：example.xls
        wb.save(excelName + ".xls")
        print("数据保存")
        code = [
            "S::(事假)",
            "C::(迟到)",
            "Q::(缺勤)",
            "B::(病假)",
        ]

    def work(self, excelName='作业'):
        # 初始化表格对象
        wb = xlwt.Workbook()
        for courseId in self.courseId_jclassIds.items():  # 多班级循环
            # 创建一个工作表，并命名courseId
            ws = wb.add_sheet(courseId[0])
            row = 0
            url = 'https://mooc1.chaoxing.com/mycourse/teachercourse?moocId=' + courseId[
                0]
            # print("1\t\t", url)
            work_list_url = self.requests.get(url, headers=self.headers)
            work_list_url = etree.HTML(
                work_list_url.text).xpath('//div/ul/li[6]/a/@href')[0]
            # print("2\t\t", work_list_url)
            # 1作业列表
            work_list_url = 'https://mooc1.chaoxing.com' + work_list_url
            # print("3\t\t", work_list_url)
            workId = self.requests.get(work_list_url, headers=self.headers)
            workId = etree.HTML(workId.text)
            encs = workId.xpath('//*[@id="options"]/li/a/@onclick')
            encs = [
                re.findall(r".*selectClass\(this,'(\w+)','(\w+)'\);", x)[0]
                for x in encs
            ]
            tb = []
            for classId in encs:  # 循环班级
                url = 'https://mooc1.chaoxing.com/work/getAllWork?courseId=%s&isdisplaytable=2&mooc=1&issue=1&chapterId=&classId=%s&isAll=0&enc=%s&dirEnc=267e402a6ff6dadb304057cbeb16eec0&ut=t'
                url = url % (courseId[0], classId[0], classId[1])
                # print("4\t\t uu", url)
                workId = self.requests.get(url, headers=self.headers)
                workId = etree.HTML(workId.text)
                # print('ff', len(workId), workId)
                workIds = workId.xpath('//*[@class="Btn_blue_1 fr"]/@href')
                # print("5\t\t", workIds)
                if len(workIds) > 1:
                    print(courseId[1][classId[0]], len(workIds), '次作业')
                    for work_url in workIds:
                        # 2查看
                        work_url = "https://mooc1.chaoxing.com" + work_url
                        # print("4\t\t", work_url)
                        work_page = self.requests.get(work_url,
                                                      headers=self.headers)
                        work_page = etree.HTML(work_page.text)
                        # 3详情
                        work_dt_url = "https://mooc1.chaoxing.com" + work_page.xpath(
                            '//*[@class="fr"]/@href')[0]
                        # print("work_dt_url:", work_dt_url)
                        work_dt = self.requests.get(work_dt_url,
                                                    headers=self.headers)
                        work_dt = etree.HTML(work_dt.text)
                        workLibraryId = work_dt.xpath(
                            '//*[@id="workLibraryId"]/@value')[0]
                        workRQId = work_dt.xpath('//div/span/a/@onclick')
                        workRQId = re.findall(r'(\d+)', workRQId[0])[0]

                        tjDetailTitle = work_dt.xpath(
                            '//*[@class="tjDetailTitle"]/text()')[0].strip()
                        # print(tjDetailTitle)

                        id = re.findall(r'.*id=(\w+).*', work_dt_url)[0]
                        # 5查看统计详情
                        url = "https://mooc1.chaoxing.com/work/viewQusetionStatisticDetail?workRelationId=%s&classId=%s&courseId=%s&workRelationQuestionId=%s&flag=&workLibraryId=%s&currentPageNum=1&isSingle=true&blankSizeGtOne=false&order=0" % (
                            id, classId[0], courseId[0], workRQId,
                            workLibraryId)
                        print(url)
                        dd = self.requests.get(url, headers=self.headers)
                        dd = etree.HTML(dd.text)
                        c1 = dd.xpath('//*/td[3]/text()')
                        c2 = dd.xpath('//*/td[4]/span/text()')
                        c3 = dd.xpath('//*/td[6]/text()')
                        tr = [[
                            tjDetailTitle,
                            courseId[1][classId[0]],
                        ] + list(x) for x in list(zip(c1, c2, c3))]
                        print(tjDetailTitle, len(c1))

                        [tb.append(x) for x in tr]

            # 遍历数据文件中的所有行
            for dd in tb:
                # 初始化列计数器
                col = 0
                # 遍历每一行数据的所有列
                for x in dd:
                    # if col == 1:
                    #     x = int(x)
                    ws.write(row, col, x)
                    # 每添加一列数据，列计数器就+1
                    col = col + 1
                # 每添加一行数据，行计数器就+1
                row = row + 1
            # 保存Excel文件，并命名为：example.xls
            wb.save(excelName + ".xls")
        print("数据保存")

    def get_info(self, courseId):
        '''
        return cpi,openc
        '''
        headers = {
            "Referer":
            "http://i.chaoxing.com",
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
        }
        url = "http://fycourse.fanya.chaoxing.com/courselist/opencourse?courseId=%s" % courseId
        page = self.requests.get(url, headers=headers)
        return {
            "cpi": re.findall(r'.*cpi=(\d{9}).*', page.text)[0],
            "openc": re.findall(r'.* openc : \'(\w+)\'*', page.text)[0]
        }


app = chaoxing()
app.login()
app.sign_in()
app.work()
